package com.caius.xiaohashu.gateway.filter;

import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Caius
 * @description 转发请求, 添加请求头的用户 ID 添加 Header 传递下游服务
 * @since Created in 2025-05-16
 */
@Component
@Slf4j
@Order(-90)
public class AddUserId2HeaderFilter implements GlobalFilter {

    private static final String HEADER_USER_ID = "userId";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("==================> TokenConvertFilter");

        Long userId = null;
        try{
            userId = StpUtil.getLoginIdAsLong();
        } catch (Exception e) {
            // 没登录直接放行
            return chain.filter(exchange);
        }
        log.info("## 当前登录的用户， userId: {} ", userId);

        Long finalUserId = userId;
        ServerWebExchange newExchange =  exchange.mutate()
                // 设置用户 ID 到请求头中间
                .request(builder -> builder.header(HEADER_USER_ID, String.valueOf(finalUserId)))
                .build();

        // 传递下一个 filter 没有修改参数
        return chain.filter(newExchange);
    }
}
